package com.newtype.meeting.client.widget.frontend;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Time;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.newtype.meeting.client.AppEvents;
import com.newtype.meeting.client.FrequencySourceData;
import com.newtype.meeting.client.model.MeetingCategory;
import com.newtype.meeting.client.model.MeetingStart;
import com.newtype.meeting.client.widget.SubjectHtml;
import com.newtype.meeting.shared.frequencySource.DateSeq;
import com.newtype.meeting.shared.frequencySource.DateValue;
import com.newtype.meeting.shared.frequencySource.DateWeek;
import com.newtype.meeting.shared.frequencySource.Frequency;
import com.newtype.meeting.shared.frequencySource.FrequencySource;
import com.newtype.meeting.shared.tools.RadioGroupConverter;

public class StartMeetingPanel extends ContentPanel {
	private FormData formData;
	private FormPanel formPanel;
	private BeanModel startBeanModel;

	private HiddenField<String> deptID;//发起人部门ID
	private TextField<String> deptName;//发起人部门Name
	private HiddenField<String> openID;//公开对象ID
	private TextField<String> openName;//公开对象
	private HiddenField<String> invitedID;//与会人员ID
	private TextArea invitedName;//与会人员姓名
	private HiddenField<String> invitedOthersID;//列会人员ID
	private TextArea invitedOthersName;//列会人员姓名
	private ComboBox<MeetingCategory> category;//会议类型
	private ListStore<MeetingCategory> cates = new ListStore<MeetingCategory>();
	//保存会议时间类别
	private ListStore<Frequency> frequecies = new ListStore<Frequency>();
	private ListStore<DateSeq> seqs = new ListStore<DateSeq>();
	private ListStore<DateWeek> weeks = new ListStore<DateWeek>();
	private ListStore<DateValue> values = new ListStore<DateValue>();

	private ComboBox<Frequency> freCombo;//单一日期/每周/每月选择框
	private ComboBox<DateSeq> seqCombo;//频率选择框
	private ComboBox<DateWeek> weekCombo;//星期选择框
	private ComboBox<DateValue> valueCombo;//日期选择框

	private DateField startDate;//开始日期
	private DateField endDate;//结束日期

	private TimeField startTime;//开始时间
	private TimeField endTime;//结束时间

	private HtmlEditor content;//议程

	public StartMeetingPanel(MeetingStart start,
			List<MeetingCategory> cateList, MeetingCategory currentCate) {
		setHeaderVisible(false);
		setLayout(new FormLayout());
		setScrollMode(Scroll.AUTO);

		createFormPanel(start, cateList, currentCate);
	}

	private void createFormPanel(MeetingStart start,
			List<MeetingCategory> cateList, MeetingCategory currentCate) {
		formData = new FormData("95%");
		formPanel = new FormPanel();
		formPanel.setHeaderVisible(false);
		formPanel.setBodyBorder(false);
		formPanel.setButtonAlign(HorizontalAlignment.CENTER);
		formPanel.setFrame(true);
		formPanel.setStyleAttribute("margin", "10px 150px 10px 150px");

		//页面主题
		String imgsrc = "images/docedit.png";
		SubjectHtml subjectHtml = new SubjectHtml("发起新会议", imgsrc, "", "", "");
		formPanel.add(subjectHtml, formData);

		deptID = new HiddenField<String>();
		deptID.setFieldLabel("部门ID");
		deptID.setName("deptID");
		formPanel.add(deptID);

		deptName = new TextField<String>();
		deptName.setFieldLabel("<b>部门</b>");
		deptName.setName("deptName");
		deptName.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				Map<String, Field<String>> department = new HashMap<String, Field<String>>();
				department.put("pDeptID", deptID);
				department.put("pDeptName", deptName);
				Dispatcher.forwardEvent(AppEvents.ToDeptTreeSingleWindow,
						department);
			}
		});
		formPanel.add(deptName, formData);

		TextField<String> originatorName = new TextField<String>();
		originatorName.setFieldLabel("<b>发起人</b>");
		originatorName.setName("originatorName");
		originatorName.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				Dispatcher.forwardEvent(AppEvents.ToPersonnelSingleWindow);
			}
		});
		formPanel.add(originatorName, formData);

		openID = new HiddenField<String>();
		openID.setFieldLabel("公开对象ID");
		openID.setName("openID");
		formPanel.add(openID);

		openName = new TextField<String>();
		openName
				.setFieldLabel("<span style='color:#FFCC00;'><b>请选择对象</b></span>");
		openName.hide();
		openName.setName("openName");
		openName.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				Map<String, Field<String>> organization = new HashMap<String, Field<String>>();
				organization.put("IDStr", openID);
				organization.put("nameStr", openName);
				Dispatcher.forwardEvent(AppEvents.ToOrganizationSeperateWindow,
						organization);
			}
		});

		Radio radio1 = new Radio();
		radio1.setBoxLabel("全公司");
		radio1.setValueAttribute("0");
		radio1.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				openName.hide();
			}
		});

		Radio radio2 = new Radio();
		radio2.setBoxLabel("自订对象");
		radio2.setValueAttribute("2");
		radio2.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				openName.show();
			}
		});

		RadioGroup openType = new RadioGroup();
		openType.setFieldLabel("<b>会议公开对象</b>");
		openType.setName("openType");
		openType.add(radio1);
		openType.add(radio2);
		openType.setValue(radio1);
		formPanel.add(openType);

		formPanel.add(openName, formData);

		category = new ComboBox<MeetingCategory>();
		category.setFieldLabel("<b>类别</b>");
		category.setEmptyText("请选择一个类别...");
		category.setEditable(false);
		category.setTriggerAction(TriggerAction.ALL);
		category.setDisplayField("categoryName");
		category.setValueField("id");
		category.setStore(cates);
		category.setSelection(cateList);
		if (currentCate != null) {
			category.setValue(currentCate);
		}
		formPanel.add(category);

		TextField<String> meetingNO = new TextField<String>();
		meetingNO.setFieldLabel("<b>会议编号</b>");
		meetingNO.setName("meetingNO");
		formPanel.add(meetingNO, formData);

		TextField<String> subject = new TextField<String>();
		subject.setFieldLabel("<b>议题</b>");
		subject.setName("subject");
		formPanel.add(subject, formData);

		TextField<String> chairName = new TextField<String>();
		chairName.setFieldLabel("<b>会议主席</b>");
		chairName.setName("chairName");
		formPanel.add(chairName, formData);

		TextField<String> recorderName = new TextField<String>();
		recorderName.setFieldLabel("<b>会议记录</b>");
		recorderName.setName("recorderName");
		formPanel.add(recorderName, formData);

		invitedID = new HiddenField<String>();
		invitedID.setFieldLabel("与会人员ID");
		invitedID.setName("invitedID");
		formPanel.add(invitedID);

		invitedName = new TextArea();
		invitedName.setFieldLabel("<b>与会人员</b>");
		invitedName.setName("invitedName");
		invitedName.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				Map<String, Field<String>> personnel = new HashMap<String, Field<String>>();
				personnel.put("accountID", invitedID);
				personnel.put("fullName", invitedName);
				Dispatcher.forwardEvent(AppEvents.ToOrganizationWindow,
						personnel);
			}
		});
		formPanel.add(invitedName, formData);

		invitedOthersID = new HiddenField<String>();
		invitedOthersID.setFieldLabel("与会人员ID");
		invitedOthersID.setName("invitedOthersID");
		formPanel.add(invitedOthersID);

		invitedOthersName = new TextArea();
		invitedOthersName.setFieldLabel("<b>列席人员</b>");
		invitedOthersName.setName("invitedOthersName");
		invitedOthersName.addListener(Events.OnClick,
				new Listener<BaseEvent>() {
					@Override
					public void handleEvent(BaseEvent be) {
						Map<String, Field<String>> personnel = new HashMap<String, Field<String>>();
						personnel.put("accountID", invitedOthersID);
						personnel.put("fullName", invitedOthersName);
						Dispatcher.forwardEvent(AppEvents.ToOrganizationWindow,
								personnel);
					}
				});
		formPanel.add(invitedOthersName, formData);

		TextArea guidance = new TextArea();
		guidance.setFieldLabel("<b>外部指导人员</b>");
		guidance.setName("guidance");
		formPanel.add(guidance, formData);

		content = new HtmlEditor();
		content.setFieldLabel("<b>议程</b>");
		content.setName("content");
		formPanel.add(content, formData);

		//创建日期时间选择
		createFrequencySource(start);

		TextField<String> location = new TextField<String>();
		location.setFieldLabel("<b>会议地点</b>");
		location.setName("location");
		formPanel.add(location);

		//设置默认值
		start.setOpenType("0");

		startBeanModel = BeanModelLookup.get().getFactory(MeetingStart.class)
				.createModel(start);

		FormBinding formBinding = new FormBinding(formPanel, true);

		//绑定状态RadioGroup
		FieldBinding statusFB = formBinding.getBinding(openType);
		statusFB.setConverter(new RadioGroupConverter(openType));

		formBinding.bind(startBeanModel);

		formPanel.addButton(getSubmitButton());
		formPanel.addButton(getSaveButton());
		if (start.getId() != null) {
			formPanel.addButton(getDeleteButton(start.getId()));
		}
		add(formPanel);
	}

	public void createFrequencySource(MeetingStart start) {
		frequecies.add(FrequencySourceData.getFrequencies());
		seqs.add(FrequencySourceData.getDateSeqs());
		weeks.add(FrequencySourceData.getDateWeeks());
		values.add(FrequencySourceData.getDateValues());

		freCombo = new ComboBox<Frequency>();
		freCombo.setDisplayField("showFrequency");
		freCombo.setSelection(FrequencySourceData.getFrequencies());
		freCombo.setWidth(100);
		freCombo.setStore(frequecies);
		freCombo.setTypeAhead(true);
		freCombo.setEditable(false);
		freCombo.setTriggerAction(TriggerAction.ALL);

		seqCombo = new ComboBox<DateSeq>();
		seqCombo.setDisplayField("showDateSeq");
		seqCombo.setSelection(FrequencySourceData.getDateSeqs());
		seqCombo.setWidth(100);
		seqCombo.setStore(seqs);
		seqCombo.setTypeAhead(true);
		seqCombo.setEditable(false);
		seqCombo.setTriggerAction(TriggerAction.ALL);
		seqCombo.hide();

		weekCombo = new ComboBox<DateWeek>();
		weekCombo.setDisplayField("showDateWeek");
		weekCombo.setSelection(FrequencySourceData.getDateWeeks());
		weekCombo.setWidth(100);
		weekCombo.setStore(weeks);
		weekCombo.setTypeAhead(true);
		weekCombo.setEditable(false);
		weekCombo.setTriggerAction(TriggerAction.ALL);
		weekCombo.hide();

		valueCombo = new ComboBox<DateValue>();
		valueCombo.setDisplayField("showDateValue");
		valueCombo.setSelection(FrequencySourceData.getDateValues());
		valueCombo.setWidth(100);
		valueCombo.setStore(values);
		valueCombo.setTypeAhead(true);
		valueCombo.setEditable(false);
		valueCombo.setTriggerAction(TriggerAction.ALL);
		valueCombo.hide();

		//开始时间选择器
		startTime = new TimeField();
		startTime.setFormat(DateTimeFormat.getFormat("HH:mm"));
		startTime.setIncrement(10);
		Time time = new Time();
		time.setText(start.getStartTime());
		startTime.setValue(time);
		startTime.setTriggerAction(TriggerAction.ALL);
		startTime.setWidth(100);

		//结束时间选择器
		endTime = new TimeField();
		endTime.setFormat(DateTimeFormat.getFormat("HH:mm"));
		endTime.setIncrement(10);
		time = new Time();
		time.setText(start.getEndTime());
		endTime.setValue(time);
		endTime.setTriggerAction(TriggerAction.ALL);
		endTime.setWidth(100);

		//存放开始日期/时间工具条
		final ToolBar startBar = new ToolBar();
		startBar.setStyleAttribute("background", "#F7F7F7");
		startBar.setBorders(false);
		startBar.setAutoHeight(true);

		startDate = new DateField();
		startDate.setName("startDate");
		startDate.setWidth(100);
		startDate.setEditable(false);

		startBar.add(new Html(getFieldLabel("开始日期:")));
		startBar.add(startDate);
		startBar.add(startTime);

		//存放结束日期/时间工具条
		final ToolBar endBar = new ToolBar();
		endBar.setStyleAttribute("background", "#F7F7F7");
		endBar.setBorders(false);
		endBar.setAutoHeight(true);

		endDate = new DateField();
		endDate.setName("endDate");
		endDate.setWidth(100);
		endDate.setEditable(false);

		endBar.add(new Html(getFieldLabel("结束日期:")));
		endBar.add(endDate);
		endBar.add(endTime);

		//存放会议时间工具条
		final ToolBar timeBar = new ToolBar();
		timeBar.setStyleAttribute("background", "#F7F7F7");
		timeBar.setBorders(false);
		timeBar.setAutoHeight(true);
		timeBar.hide();

		//当修改时展现
		String frequency = String.valueOf(start.getNFrequency());
		String datevalue = String.valueOf(start.getNDateValue());
		String dateseq = String.valueOf(start.getNDateSeq());
		if (start.getNDateType() != null) {
			freCombo.setValue(FrequencySourceData.getFrequency(frequency));
			if (frequency.equals("1")) {
				weekCombo.setValue(FrequencySourceData.getDateWeek(datevalue));
				weekCombo.show();
			} else if (frequency.equals("2")) {
				if (dateseq.equals("100")) {
					seqCombo.setValue(FrequencySourceData.getDateSeq(dateseq));
					seqCombo.show();
					valueCombo.setValue(FrequencySourceData
							.getDateValue(datevalue));
					valueCombo.show();
				} else {
					seqCombo.setValue(FrequencySourceData.getDateSeq(dateseq));
					seqCombo.show();
					weekCombo.setValue(FrequencySourceData
							.getDateWeek(datevalue));
					weekCombo.show();
				}
			}
		}

		freCombo
				.addSelectionChangedListener(new SelectionChangedListener<Frequency>() {
					@Override
					public void selectionChanged(
							SelectionChangedEvent<Frequency> se) {
						String freStr = se.getSelectedItem().getFrequency();
						if (freStr.equals("1")) {
							weekCombo.show();
							seqCombo.hide();
							valueCombo.hide();

							timeBar.removeAll();
							timeBar.add(new Html(getFieldLabel("会议时间:")));
							timeBar.add(startTime);
							timeBar.add(endTime);
							timeBar.show();
						} else if (freStr.equals("2")) {
							weekCombo.hide();
							seqCombo.reset();
							seqCombo.show();
							valueCombo.show();

							timeBar.removeAll();
							timeBar.add(new Html(getFieldLabel("会议时间:")));
							timeBar.add(startTime);
							timeBar.add(endTime);
							timeBar.show();
						} else {
							weekCombo.hide();
							seqCombo.hide();
							valueCombo.hide();

							startBar.removeAll();
							startBar.add(new Html(getFieldLabel("开始日期:")));
							startBar.add(startDate);
							startBar.add(startTime);
							endBar.removeAll();
							endBar.add(new Html(getFieldLabel("结束日期:")));
							endBar.add(endDate);
							endBar.add(endTime);
							timeBar.hide();
						}
					}
				});

		seqCombo
				.addSelectionChangedListener(new SelectionChangedListener<DateSeq>() {
					@Override
					public void selectionChanged(
							SelectionChangedEvent<DateSeq> se) {
						String seqStr = se.getSelectedItem().getDateSeq();
						if (seqStr.equals("100")) {
							valueCombo.show();
							weekCombo.hide();
						} else {
							weekCombo.show();
							valueCombo.hide();
						}
					}
				});

		//存放会议类型选择框
		ToolBar toolBar = new ToolBar();
		toolBar.setStyleAttribute("background", "#F7F7F7");
		toolBar.setBorders(false);
		toolBar.setAutoHeight(true);

		toolBar.add(new Html(getFieldLabel("时间类别:")));
		toolBar.add(freCombo);
		toolBar.add(seqCombo);
		toolBar.add(weekCombo);
		toolBar.add(valueCombo);

		//添加工具条
		formPanel.add(toolBar, formData);
		formPanel.add(startBar, formData);
		formPanel.add(endBar, formData);
		formPanel.add(timeBar, formData);
	}

	//删除草稿按钮
	private Button getDeleteButton(final String id) {
		Button button = new Button("删除草稿");
		button.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Dispatcher.forwardEvent(AppEvents.DeleteDraft, id);
			}
		});
		return button;
	}

	//送出按钮
	private Button getSubmitButton() {
		Button button = new Button("送出，并进行时间冲突检查");
		button.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Dispatcher.forwardEvent(AppEvents.SaveMeeting,
						getMeetingStart());
			}
		});
		return button;
	}

	//暂存草稿按钮
	private Button getSaveButton() {
		Button button = new Button("暂存草稿");
		button.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Dispatcher.forwardEvent(AppEvents.MeetingScratchtape,
						getMeetingStart());
			}
		});
		return button;
	}

	/**
	 * 获取表单的值并赋给MeetingStart对象
	 * @return MeetingStart
	 */
	private MeetingStart getMeetingStart() {
		//新建一个MeetingStart对象
		MeetingStart start = startBeanModel.getBean();
		start.setDeptID(deptID.getValue());//发起人部门ID
		start.setDeptName(deptName.getValue());//发起人部门Name
		start.setOpenID(openID.getValue());//公开对象ID
		start.setOpenName(openName.getValue());//公开对象Name
		start.setCategoryID((String) category.getSelection().get(0).get("id"));//获取会议类型
		start.setInvitedID(invitedID.getValue());//与会人员ID
		start.setInvitedName(invitedName.getValue());//与会人员Name
		start.setInvitedOthersID(invitedOthersID.getValue());//列席人员ID
		start.setInvitedOthersName(invitedOthersName.getValue());//列席人员Name
		start.setContent(content.getValue());//会议内容
		start.setStartTime(startTime.getValue().getText());//会议开始时间
		start.setEndTime(endTime.getValue().getText());//会议结束时间

		FrequencySource source = getFrequencySource();
		start.setNDateType(Integer.parseInt(source.getDateType()));
		start.setNFrequency(Integer.parseInt(source.getFrequency()));
		start.setNDateSeq(Integer.parseInt(source.getDateSeq()));
		start.setNDateMonth(Integer.parseInt(source.getDateMonth()));
		start.setNDateValue(Integer.parseInt(source.getDateValue()));
		return start;
	}

	public FrequencySource getFrequencySource() {
		//从表单中获取值
		String frequency = freCombo.getValue().getFrequency();
		String dateSeq = seqCombo.getValue().getDateSeq();
		String dateWeek = weekCombo.getValue().getDateWeek();
		String dateValue = valueCombo.getValue().getDateValue();
		//实例化一个FrequencySource用来存储表单信息
		FrequencySource source = null;
		if (frequency.equals("0")) {
			source = new FrequencySource(frequency, frequency, "0", "0", "0");
		} else if (frequency.equals("1")) {
			source = new FrequencySource(frequency, frequency, "0", dateWeek,
					"0");
		} else if (frequency.equals("2")) {
			if (dateSeq.equals("100")) {
				source = new FrequencySource(frequency, frequency, dateSeq,
						dateValue, "0");
			} else {
				source = new FrequencySource(frequency, frequency, dateSeq,
						dateWeek, "0");
			}
		}
		return source;
	}

	public String getFieldLabel(String str) {
		return "<span style='background-color:#F7F7F7;display:-moz-inline-box;display:inline-block;width:78px;font-size:12px;font-weight:bold;'>"
				+ str + "</span>";
	}

	public ListStore<MeetingCategory> getCates() {
		return cates;
	}

}
